<template>
  <a-modal
    v-model:open="localVisible"
    :title="modalTitle"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitLoading"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
    >
      <a-form-item label="用户名" name="username" required>
        <a-input 
          v-model:value="formState.username" 
          placeholder="请输入用户名" 
          :disabled="formState.id && formState.id !== null" 
        />
      </a-form-item>
      <a-form-item 
        label="密码" 
        name="password" 
        :required="formState.id === null"
      >
        <a-input-password 
          v-model:value="formState.password" 
          placeholder="请输入密码" 
        />
        <div v-if="formState.id" class="form-help-text">不修改密码请留空</div>
      </a-form-item>
      <a-form-item label="姓名" name="name" required>
        <a-input v-model:value="formState.name" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';


// 创建本地表单ref引用
const formRef = ref(null);

const props = defineProps({
  modalTitle: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  },
  formState: {
    type: Object,
    default: () => ({})
  },
});
const emit = defineEmits(['update:visible', 'submit', 'cancel']);

// 加载状态
const submitLoading = computed(() => props.loading);
// 动态表单验证规则
const rules = computed(() => ({
  username: [{ required: true, message: '请输入用户名' }],
  password: props.formState.id 
    ? [] // 编辑模式下不校验密码必填
    : [{ required: true, message: '请输入密码' }],
  name: [{ required: true, message: '请输入姓名' }],
  email: [{ type: 'email', message: '请输入正确的邮箱格式' }]
}));

// 使用计算属性代理visible属性
const localVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 提交表单
const handleSubmit = () => {
  console.log('submitData',{...props.formState})
  formRef.value?.validate().then(() => {
    const submitData = { ...props.formState };
    // 如果是编辑模式且密码为空，删除密码字段
    if (submitData.id && !submitData.password) {
      delete submitData.password;
    }
    emit('submit', submitData);
  }).catch(err => {
    console.error('表单验证失败:', err);
  });
};

// 取消操作
const handleCancel = () => {
  // resetForm();
  emit('cancel');
};

// 重置表单
const resetFields = () => {
  formRef.value?.resetFields();
};

// 暴露方法给父组件
defineExpose({
  validate: () => formRef.value?.validate(),
  resetFields,
  formRef
});
</script>

<style scoped>
.form-help-text {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style> 